package org.zn.mvcbase.config;

import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.zn.mvcbase.config.property.BootMvcProperty;
import org.zn.mvcbase.config.property.Rest;
import org.zn.mvcbase.rest.RestEntityFactroy;
import org.zn.mvcbase.rest.spi.RestStatusHandlerChain;

import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@ConditionalOnProperty(prefix=BootMvcProperty.BOOT_PREFIX+Rest.REST_PREFIX,name="entity",havingValue="true")
@EnableConfigurationProperties(value =  {BootMvcProperty.class})
public class RestEntityFactroyConfig {
	
	private static transient final Logger log = LoggerFactory.getLogger(RestEntityFactroyConfig.class);

	@Autowired
	private BootMvcProperty bootMvcProperty;
	
	@Bean
	@ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper objectMapper(){
        return new ObjectMapper();
    }
	
	@PostConstruct
	public void initLog() {
		
		log.info("{} init","RestEntityFactroyConfig");
		
	}
	

	@ConditionalOnProperty(prefix=BootMvcProperty.BOOT_PREFIX+Rest.REST_PREFIX,name="template" ,havingValue="true")
	@Bean()
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

	
	@ConditionalOnProperty(prefix=BootMvcProperty.BOOT_PREFIX+Rest.REST_PREFIX,name="template" ,havingValue="true")
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(bootMvcProperty.getRest().getReadtimeout());//单位为ms
        factory.setConnectTimeout(bootMvcProperty.getRest().getConnectTimeout());//单位为ms
        return factory;
    }
	
    
    @Bean
    public RestEntityFactroy restEntityFactroy(RestTemplate restTemplate,ObjectMapper om,ObjectProvider<List<RestStatusHandlerChain>> objectProvider){
      
    	List<RestStatusHandlerChain>  handlers=objectProvider.getIfAvailable();
    	
    	RestEntityFactroy ref= new RestEntityFactroy(restTemplate, om);
    	
    	ref.setRestStatusHandler(handlers);
    	
    	return ref;

    }

    
 

    

}
